package cn.tedu.tmall.admin.content.handler;

import cn.tedu.tmall.common.web.JsonResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

/**
 * 全局异常处理器
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 处理运行时异常  运行时的异常太多了.大,
     * 变小 自定义异常 todo
     * @param e
     * @return
     */
    @ExceptionHandler
    public JsonResult handleRuntimeException(RuntimeException e){
        log.error("捕获RuntimeException",e);
        String message = e.getMessage();
        return JsonResult.fail(message);
    }

    /**
     * 处理 MethodArgumentNotValidException
     */
    @ExceptionHandler
    public JsonResult handleMethodArgumentNotValidException(MethodArgumentNotValidException e){
        log.error("捕获MethodArgumentNotValidException",e);
        List<FieldError> fieldErrors = e.getFieldErrors();
        StringBuffer allMessage = new StringBuffer();
        for (FieldError fieldError : fieldErrors) {
            allMessage.append(fieldError.getDefaultMessage());
            allMessage.append(",");
        }
        //类别名称不能太长-ByLength,类别名称不能为空-byBlank,类别名称不能为空-byEmpty,类别名称不能太长-BySize,年龄应该在18-120之间,
        return JsonResult.fail(delete(allMessage));
    }

    public String delete(StringBuffer str) {
        //StringBuilder StringBuffer 区别  StringBuffer 线程安全
        StringBuffer stringBuffer = new StringBuffer(str);
        StringBuffer delete = stringBuffer.
                delete(stringBuffer.lastIndexOf(","), stringBuffer.length());
       return delete.toString();
    }


}
